package com.navi.core.util;

import com.sun.javafx.binding.StringFormatter;
import javafx.beans.binding.StringExpression;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Matthew on 2017/9/22.
 */
public class ReadWriteFileUtil {

    public static void replaceTxtFile(File readFile, File writeFile, String preStr, String replaceStr, int startIndex, String mode, String modulus) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(readFile), "UTF-8"));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writeFile), "UTF-8"));
        boolean updateFlag = false;
        int length = 0;
        int lineCount = 0;
        boolean updatePanelFlag = false;
        for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
            lineCount++;
            if (mode.equals("UPDATE_DEFECT_CODE")) {
                if (line.startsWith("%")) {
                    updateFlag = true;
                    length = 12;
                    bufferedWriter.write(line);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                    continue;
                } else if (line.startsWith("#")) {
                    updateFlag = false;
                } else if (line.startsWith("@")) {
                    break;
                }
            } else if (mode.equals("UPDATE_PANEl_JGEGRD")) {
                if (line.startsWith("#") && !updatePanelFlag) {
                    updateFlag = true;
                    length = 3;
                    bufferedWriter.write(line);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                    continue;
                } else if (line.startsWith("@")) {
                    break;
                }
            } else if (mode.equals("UPDATE_GLASS_JGEGRD")) {
                if (lineCount == 3) {
                    updateFlag = true;
                    length = 3;
                }
            }
            if (updateFlag) {
                if (mode.equals("UPDATE_DEFECT_CODE")) {
                    String pending = line.substring(startIndex, startIndex + preStr.length());
                    if (pending.equals(preStr)) {
                        bufferedWriter.write(replaceString(line, replaceStr, startIndex, length));
                    } else {
                        bufferedWriter.write(line);
                    }
                } else if (mode.equals("UPDATE_PANEl_JGEGRD")) {
                    if (line.length() > 12) {
                        String m = line.substring(10, 12);
                        if (modulus.equals(m)) {
                            bufferedWriter.write(replaceString(line, replaceStr, startIndex, length));
                            updatePanelFlag = true;
                        } else {
                            bufferedWriter.write(line);
                        }
                        updateFlag = false;
                    } else {
                        bufferedWriter.write(line);
                    }
                } else if (mode.equals("UPDATE_GLASS_JGEGRD")) {
                    bufferedWriter.write(replaceString(line, replaceStr, startIndex, length));
                    updateFlag = false;
                }
                bufferedWriter.newLine();
                bufferedWriter.flush();
            } else {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }
        }
        bufferedReader.close();
        bufferedWriter.close();
    }

    public static void appendContent(String fileName, String content) {
        try {
// 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度，字节数
            long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content + "\r\n");
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void replaceTextContent(String fileName, String filePath, String preStr, String rStr, int startIndex, String name, String mode, String modulus, String indexPath, String indexContent) throws IOException {
        File writeFile = new File(filePath + fileName + ".TXT");
        File readFile = new File(filePath + name + ".TXT");
        System.currentTimeMillis();
        replaceTxtFile(readFile, writeFile, preStr, rStr, startIndex, mode, modulus);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
        String time = formatter.format(LocalDateTime.now());
        String content = time + " " + indexContent;
        appendContent(indexPath, content);
    }

    public static void overwriteFileForCode(String newFile, String fileName, String filePath, String newCode, String x_point, String y_point, String indexPath, String indexContent) throws Exception {
        File writeFile = new File(filePath + newFile + ".TXT");
        writeFile.createNewFile();
        File readFile = new File(filePath + fileName + ".TXT");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(readFile), "UTF-8"));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writeFile), "UTF-8"));
        String b = null;
        ArrayList<String> fileList = new ArrayList<>();
        int flag = 0;
        while ((b = bufferedReader.readLine()) != null) {
            if (flag == 1) {
                String cont_1 = b.substring(12,26);
                String cont_2 = b.substring(38);
                String code = String.format("%-12s", newCode);
                b = code + cont_1 + code + cont_2;
                flag = 0;
            }
            if (b.contains(x_point) && b.contains(y_point)) {
                flag ++;
            }
            fileList.add(b);
        }
        for (int i = 0; i < fileList.size(); i++) {
            String content = fileList.get(i);
            bufferedWriter.write(content);
            bufferedWriter.newLine();
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
        String time = formatter.format(LocalDateTime.now());
        String content = time + " " + indexContent;
        appendContent(indexPath, content);

    }

    public static void overwriteAllFileForCode(String newFile, String fileName, String filePath, String newCode, List<List<String>> points, String indexPath, String indexContent, String flagC) throws Exception {
        File writeFile = new File(filePath + newFile + ".TXT");
        writeFile.createNewFile();
        File readFile = new File(filePath + fileName + ".TXT");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(readFile), "UTF-8"));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writeFile), "UTF-8"));
        String b = null;
        ArrayList<String> fileList = new ArrayList<>();
        int flag = 0;
        while ((b = bufferedReader.readLine()) != null) {
            if (flag == 1) {
                String cont_1 = b.substring(12,26);
                String cont_2 = b.substring(38);
                String code ="";
                if ("No".equals(flagC)) {
                    code = String.format("%-12s", "JUNO");
                } else {
                    code = String.format("%-12s", newCode);
                }
                b = code + cont_1 + code + cont_2;
                flag = 0;
            }
            for (List<String> point : points) {
                String x_point = point.get(0);
                String y_point = point.get(1);
                if (b.contains(x_point) && b.contains(y_point)) {
                    flag ++;
                }
            }

            fileList.add(b);
        }
        for (int i = 0; i < fileList.size(); i++) {
            String content = fileList.get(i);
            bufferedWriter.write(content);
            bufferedWriter.newLine();
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
        String time = formatter.format(LocalDateTime.now());
        String content = time + " " + indexContent;
        appendContent(indexPath, content);

    }

    public static String replaceString(String str, String rstr, int startIndex, int length) {
        rstr = filling(rstr, length);
        int endIndex = startIndex + length;
        String result = str.substring(0, startIndex) + rstr + str.substring(endIndex, str.length());
//    System.out.println("修改后:" + result);
        return result;
    }

    public static String filling(String str, int length) {
        if (str.length() < length) {
            int count = length - str.length();
            for (int i = 0; i < count; i++) {
                str += " ";
            }
        }
        return str;
    }

    public static void main(String[] arg) throws IOException {
//    修改defect code
//    replaceTextContent("D://test//A1853A149500601.TXT","PH SkMu","haku",0,"A1853A149500601","UPDATE_DEFECT_CODE","");
//    修改panel judge and grade
//    replaceTextContent("D://test//A1853A149500601.TXT","* *","N S",13,"A1853A149500601","UPDATE_PANEl_JGEGRD","02");
//    修改glass judge and grade
//    replaceTextContent("D://test//A1853A149500601.TXT","*** ","N S*",79,"A1853A149500601","UPDATE_GLASS_JGEGRD","");
    }
}